package java_concurrency_program_design_in_practice.atomic_reference;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 带有时间戳的对象引用<br/>
 * 它可以保证你在修改对象引用时的安全性<br/>
 * @author lixiangke
 * @date 2017/12/8
 */
public class AtomicStampedReferenceDemo {
    static AtomicStampedReference<Integer> money = new AtomicStampedReference<>(19, 0);

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            final int timestamp = money.getStamp();

            new Thread() {
                @Override
                public void run() {
                    while (true) {
                        while (true) {
                            sleepMillis(1100);
                            Integer m = money.getReference();
                            if (m < 20) {
                                if (money.compareAndSet(m, m + 20, timestamp, timestamp + 1)) {
                                    System.out.println("余额小于20, 余额充值成功, 余额: " + money.getReference());
                                    break;
                                }
                            } else {
                                // 余额大于20元, 无需充值
                                break;
                            }
                        }
                    }
                }
            }.start();
        }

        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    while (true) {
                        sleepMillis(1000);
                        int timestamp = money.getStamp();
                        Integer m = money.getReference();
                        if (m > 10) {
                            if (money.compareAndSet(m, m - 10, timestamp, timestamp + 1)) {
                                System.out.println("大于10元, 消费10元");
                                break;
                            }
                        } else {
                            System.out.println("没有足够余额");
                            break;
                        }
                    }
                }
            }
        }.start();
    }

    static void sleepMillis(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

